import 'dart:isolate';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:system_alert_window/system_alert_window.dart';
import '../logs/Logger.dart';


class TranslationOverLay extends StatefulWidget {
  @override
  State<TranslationOverLay> createState() => TranslationOverLayState();
}

class TranslationOverLayState extends State<TranslationOverLay> {

  static const String _mainAppPort = 'MainApp';
  SendPort? mainAppPort;
  bool update = false;

  SystemWindowPrefMode prefMode = SystemWindowPrefMode.OVERLAY;

  final _receivePort = ReceivePort();
  SendPort? homePort;
  String? latestMessageFromOverlay;

  String finalFromLanguage = '';
  String finalToLanguage = '';



  ScrollController scrollControllerTop = ScrollController();
  // ScrollController scrollControllerBottom = ScrollController();

  @override
  void initState() {
    super.initState();

    if (homePort != null) return;

    final res = IsolateNameServer.registerPortWithName(
      _receivePort.sendPort,
      _mainAppPort,
    );

    logger.info("$res: OVERLAY");


    _receivePort.listen((message) async {
      logger.info("message from OVERLAY: $message");
      print('OverLay refresh ... 1 ');

      await SystemAlertWindow.sendMessageToOverlay(message);
      print('OverLay refresh ... 2 ');



      print('OverLay finalFromLanguage : ${finalFromLanguage}, finalToLanguage: ${finalToLanguage}');


    });


    SystemAlertWindow.overlayListener.listen((message) {
      logger.info("$message in overlay");
      setState(() {
        finalFromLanguage = message['finalFromLanguage'];
        finalToLanguage = message['finalToLanguage'];
        // 延迟到下一帧执行，确保布局完成
        SchedulerBinding.instance.addPostFrameCallback((_) {
          _autoScrollToTop();
          // _autoScrollToBottom();
        });
      });
    });
  }

  void _autoScrollToTop() {
    // 使用 animateTo 实现平滑滚动
    scrollControllerTop.animateTo(
      scrollControllerTop.position.maxScrollExtent,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeOut,
    );
  }


  /*void _autoScrollToBottom() {
    // 使用 animateTo 实现平滑滚动
    scrollControllerBottom.animateTo(
      scrollControllerBottom.position.maxScrollExtent,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeOut,
    );
  }*/

  void callBackFunction(String tag) {
    print("Got tag " + tag);
    mainAppPort ??= IsolateNameServer.lookupPortByName(
      _mainAppPort,
    );
    mainAppPort?.send('Date: ${DateTime.now()}');
    mainAppPort?.send(tag);
  }

  @override
  Widget build(BuildContext context) {
    print('OverLay refresh ... 3 ');
    return Scaffold(
      body: overlay(),
    );
  }


  Widget overlay() {
    return Container(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.only(right: 10,left: 10),
      color: Colors.black,
      child: Stack(
        children: [
          Positioned(child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                padding: EdgeInsets.only(right: 20,left: 20,bottom: 60),
                width: 350,
                height: 200,
                child: SingleChildScrollView(
                  controller: scrollControllerTop,
                  child: finalFromLanguage.trim() != '' ?  Text(finalFromLanguage + '\n' + finalToLanguage,style: TextStyle(
                      color: Colors.white)
                  ):
                  Text('Waiting ...',style: TextStyle(
                      color: Colors.white
                  ),),
                ),
              ),
             /* Container(
                padding: EdgeInsets.only(right: 20,left: 20),
                width: 350,
                height: 100,
                child: SingleChildScrollView(
                  controller: scrollControllerBottom,
                  child: finalToLanguage.trim() != ''?
                  Text(finalToLanguage,style: TextStyle(
                    color: Colors.white,
                  )):  SizedBox(),
                ),
              )*/
            ],
          ),top: 50),
          Positioned(child: GestureDetector(
              onTap: () {
                  SystemAlertWindow.closeSystemWindow();
              },
              child: Text('关闭',style: TextStyle(color: Colors.white)),
          ),
          top: 20, left: 20,)
        ],
      ),
    );
  }
  
}